importgreenfoot.*;// (World, Actor, GreenfootImage, and Greenfoot)importjava.awt.Color;importjava.util.Random;/**
* A pile of food. The pile consists initially of 100 crumbs of food.
*
* @author Michael Kolling
* @version 1.1
*/publicclass Food extends Actor
{privatestaticfinalint SIZE =30;privatestaticfinalint HALFSIZE = SIZE /2;privatestaticfinalColor color1 =newColor(160, 200, 60);privatestaticfinalColor color2 =newColor(80, 100, 30);privatestaticfinalColor color3 =newColor(10, 50, 0);privatestaticfinalRandom randomizer =newRandom();privateint crumbs =100;// number of bits of food in this pile/**
* Create a pile of food with an image depicting the amount.
*/public Food(){
updateImage();}/**
* Remove some food from this pile of food.
*/publicvoid takeSome(){
crumbs = crumbs -3;if(crumbs <=0){
getWorld().removeObject(this);}else{
updateImage();}}/**
* Update the image
*/privatevoid updateImage(){
GreenfootImage image =new GreenfootImage(SIZE, SIZE);for(int i =0; i < crumbs; i++){int x = randomCoord();int y = randomCoord();
image.setColorAt(x, y, color1);
image.setColorAt(x +1, y, color2);
image.setColorAt(x, y +1, color2);
image.setColorAt(x +1, y +1, color3);}
setImage(image);}/**
* Returns a random number relative to the size of the food pile.
*/privateint randomCoord(){int val = HALFSIZE +(int)(randomizer.nextGaussian()*(HALFSIZE /2));if(val <0)return0;if(val > SIZE -2)return SIZE -2;elsereturn val;}}
返回